package cn.kent.base.sleep;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 验证线程睡眠的时候，仍然持有 锁
 */
public class SleepTest {
    // 创建一个独占锁
    private static final Lock lock = new ReentrantLock(false);

    public static void main(String[] args) {
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                // 获取独占锁
                lock.lock();
                try {
                    System.out.println("ThreadA is in sleep");
                    Thread.sleep(10000);
                    System.out.println("ThreadA is in awaked");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // 释放锁
                    lock.unlock();
                }
            }
        });

        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                // 获取独占锁
                lock.lock();
                try {
                    System.out.println("ThreadB is in sleep");
                    Thread.sleep(10000);
                    System.out.println("ThreadB is in awaked");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // 释放锁
                    lock.unlock();
                }
            }
        });

        threadA.start();
        threadB.start();
    }
}
